package arithmetic;

import java.util.Set;
import java.util.Stack;

import com.google.common.collect.Sets;

/**
 * 正确的字符.  .
 * 给定一个只包括 '(', ')', '[',']','{}','}' 的字符串，判断字符串是否有效。
 * 有效字符串需满足：
 * 左括号必须用相同类型的右括号闭合。
 * 左括号必须以正确的顺序闭合。
 * 注意空字符串可被认为是有效字符串
 *
 * @author jiangfeng on 2022/3/3
 */
public class StackTest {
    public static void main(String[] args) {
        // "()", "{(}",""
        System.out.println(new StackTest().solution("()"));
        System.out.println(new StackTest().solution("[]"));
        System.out.println(new StackTest().solution("{}"));
        System.out.println(new StackTest().solution("(}"));
        System.out.println(new StackTest().solution("({)}"));
        System.out.println(new StackTest().solution("{()}"));
        System.out.println(new StackTest().solution("{[()]}"));
    }

    static final Character SMALL_L = '(';
    static final Character SMALL_R = ')';
    static final Character MEDIUM_L = '[';
    static final Character MEDIUM_R = ']';
    static final Character BIG_L = '{';
    static final Character BIG_R = '}';

    static final Set<Character> L = Sets.newHashSet(SMALL_L, MEDIUM_L, BIG_L);
    // 思路压栈的操作
    public boolean solution(String s){

        Stack stack = new Stack();
        char[] chars = s.toCharArray();

        for (char aChar : chars) {
            if(L.contains(aChar)){
                stack.push(aChar);
                continue;
            }
            if(SMALL_R.equals(aChar)){
                if(stack.isEmpty()){
                    return false;
                }
                if(!stack.pop().equals(SMALL_L)){
                    return false;
                }
            }
            if(MEDIUM_R.equals(aChar)){
                if(stack.isEmpty()){
                    return false;
                }
                if(!stack.pop().equals(MEDIUM_L)){
                    return false;
                }
            }
            if(BIG_R.equals(aChar)){
                if(stack.isEmpty()){
                    return false;
                }
                if(!stack.pop().equals(BIG_L)){
                    return false;
                }
            }
        }
        if(stack.isEmpty()){
            return true;
        }
        return false;
    }


}
